import * as express from 'express';
import * as bodyParser from 'body-parser';
import { Request, Response } from 'express';
import { AppDataSource } from '@/data-source';
import { Routes } from '@/routes';
import { Role } from '@/entity/Role';
import { Menu } from '@/entity/Menu';
import { Goods } from '@/entity/Goods';

const express = require('express');
const cors = require('cors');
AppDataSource.initialize()
  .then(async () => {
    // create express app
    const app = express();

    app.use(
      cors({
        credentials: true,
      })
    );
    app.use(bodyParser.json({ limit: '1mb' }));
    app.use(bodyParser.urlencoded({ extended: true, limit: '1mb' }));

    // register express routes from defined application routes
    Routes.forEach((route) => {
      (app as any)[route.method](
        `/api${route.route}`,
        (req: Request, res: Response, next: Function) => {
          const result = new (route.controller as any)()[
            route.action
          ](req, res, next);
          if (result instanceof Promise) {
            result.then((result) =>
              result !== null && result !== undefined
                ? res.send(result)
                : undefined
            );
          } else if (result !== null && result !== undefined) {
            res.json(result);
          }
        }
      );
    });
    app.listen(1107);
    // await initSymptoms()
    // await AppDataSource.manager.save(
    //   AppDataSource.manager.create(Menu, {
    //     menu_name: '默认分类',
    //   })
    // );

    // await AppDataSource.manager.save(
    //   AppDataSource.manager.create(Goods, {
    //     name: '菠萝炒番茄',
    //     description: '谁不喜欢菠萝炒番茄我都会伤心',
    //     price: 30,
    //   })
    // );

    // 获取现有的症状
    // const symptom1 = await AppDataSource.manager.findOne(Symptom, {
    //   where: { symptom_name: '花粉症' },
    // });
    // const symptom2 = await AppDataSource.manager.findOne(Symptom, {
    //   where: { symptom_name: '糖尿病' },
    // });

    // 创建并保存用户
    // const user = AppDataSource.manager.create(User, {
    //     username: 'Phantom',
    //     password: 'Assassin',
    //     name: 'Phantom',
    //     phone: '123456789',
    //     sex: 1,
    //     symptom_list: [symptom1, symptom2], // 添加症状
    // });

    // await AppDataSource.manager.save(user);

    console.log(
      'Express server has started on port 1107. Open http://localhost:3000/users to see results'
    );
  })
  .catch((error) => console.log(error));
